
class MarketManager {
    constructor() {
        this.marketUser = null;
        this.allPlugins = [];
        this.filteredPlugins = [];
        this.categories = [];
        this.categoriesLoaded = false; // 防止无限递归加载分类
        this.localPlugins = []; // 本地列表
        this.currentType = ''; // plugin, template, ''
        this.currentCategory = '';
        this.currentPrice = '';
        this.checkLoginStatus();
        this.init();
    }

    /**
     * 初始化
     */
    async init() {
        await this.loadLocalPlugins();
        this.loadMarketPlugins(1);
    }

    /**
     * 加载本地列表
     */
    async loadLocalPlugins() {
        const response = await fetch('/adminapi/plugin/manager/getList');
        const data = await response.json();

        // 根据实际返回的数据结构进行处理
        if (data.code === 1) {
            // 如果有code字段且为1
            this.localPlugins = data.data?.plugins || data.plugins || [];
        } else if (data.plugins) {
            // 如果直接有plugins字段
            this.localPlugins = data.plugins;
        } else if (Array.isArray(data)) {
            // 如果直接返回数组
            this.localPlugins = data;
        } else {
            this.localPlugins = [];
        }
    }

    /**
     * 检查登录状态
     */
    checkLoginStatus() {
        // 调用API检查登录状态
        fetch('/adminapi/plugin/auth/checkLogin')
            .then(response => response.json())
            .then(data => {
                if (data.code === 1 && data.data.is_login) {
                    this.marketUser = data.data.user_info;
                    this.marketUser.email = data.data.email;
                    this.marketUser.token = data.data.token;
                    this.saveLoginData(this.marketUser);
                } else {
                    this.clearLoginData();
                    this.marketUser = null;
                }
            })
            .catch(error => {
                this.clearLoginData();
                this.marketUser = null;
            });
    }

    /**
     * 保存登录数据到localStorage
     */
    saveLoginData(userData) {
        localStorage.setItem('plugin_market_login', JSON.stringify({
            email: userData.email,
            token: userData.token,
            user_info: userData,
            timestamp: Date.now()
        }));
    }

    /**
     * 从localStorage获取登录数据
     */
    getLoginData() {
        try {
            const data = localStorage.getItem('plugin_market_login');
            if (data) {
                const loginData = JSON.parse(data);
                // 检查是否过期（7天）
                if (Date.now() - loginData.timestamp > 7 * 24 * 60 * 60 * 1000) {
                    this.clearLoginData();
                    return null;
                }
                return loginData;
            }
        } catch (e) {
            this.clearLoginData();
        }
        return null;
    }

    /**
     * 清除登录数据
     */
    clearLoginData() {
        localStorage.removeItem('plugin_market_login');
    }

    /**
     * 加载分类数据
     */
    async loadCategories() {
        try {
            // 调用main项目的分类API
            const response = await fetch('/adminapi/plugin/market/getCategories');
            const data = await response.json();

            if (data.code === 1) {
                this.categories = data.data || [];
            } else {
                // console.warn('获取分类失败:', data.msg);
                this.categories = [];
            }
        } catch (error) {
            // console.error('加载分类失败:', error);
            this.categories = [];
        }

        // 无论成功失败都渲染分类标签
        this.renderCategoryTags();
    }

    /**
     * 渲染分类标签
     */
    renderCategoryTags() {
        const container = document.getElementById('categoryTags');
        if (!container) return;

        let html = '<button type="button" class="btn btn-soft-primary btn-sm active" data-category="" onclick="selectCategory(this, \'\')">全部</button>';

        // 检查分类数据是否存在
        if (!this.categories || this.categories.length === 0) {
            container.innerHTML = html;
            return;
        }

        // 根据当前类型筛选分类
        let filteredCategories = [];

        if (this.currentType === 'plugin') {
            // 插件分类
            filteredCategories = this.categories.filter(cat =>
                cat.type === 'plugin' || cat.category_type === 'plugin' ||
                (!cat.type && !cat.category_type) // 兼容没有type字段的情况
            );
        } else if (this.currentType === 'template') {
            // 模板分类
            filteredCategories = this.categories.filter(cat =>
                cat.type === 'template' || cat.category_type === 'template'
            );
        } else {
            // 全部分类
            filteredCategories = this.categories;
        }

        filteredCategories.forEach(category => {
            const categoryId = category.id || category.category_id;
            const categoryName = category.name || category.category_name || '未知分类';
            html += `<button type="button" class="btn btn-soft-primary btn-sm" data-category="${categoryId}" onclick="selectCategory(this, '${categoryId}')">${categoryName}</button>`;
        });

        container.innerHTML = html;
    }



    /**
     * 显示加载状态
     */
    showTableLoading() {
        const container = document.getElementById('marketPlugins');
        if (container) {
            container.innerHTML = `
                <div class="loading-card">
                    <div class="loading">正在加载市场...</div>
                </div>
            `;
        }
    }

    /**
     * 显示错误信息
     */
    showError(message) {
        const container = document.getElementById('marketPlugins');
        if (container) {
            container.innerHTML = `
                <div class="error-card">
                    <div class="error-state">
                        <div class="icon">⚠️</div>
                        <h3>加载失败</h3>
                        <p>${message}</p>
                        <button class="btn btn-primary" onclick="window.marketManager.loadMarketPlugins()">重试</button>
                    </div>
                </div>
            `;
        }
    }

    /**
     * 渲染市场表格
     */
    renderMarketTable() {
        const tbody = document.querySelector('#marketTable tbody');
        if (!tbody) return;

        if (this.filteredPlugins.length === 0) {
            tbody.innerHTML = `<tr><td colspan="7" class="text-center">
                <div class="empty-state">
                    <div class="icon">🔍</div>
                    <h5>暂无内容</h5>
                    <p>没有找到符合的内容</p>
                </div>
            </td></tr>`;
            this.renderPagination();
            return;
        }

        let html = '';
        this.filteredPlugins.forEach(plugin => {
            const price = parseFloat(plugin.price) || 0;
            const priceText = price > 0 ? `¥${price}` : '免费';
            const downloads = plugin.downloads || 0;
            const categoryName = plugin.category?.name || '未分类';

            // 检查本地是否已安装（通过slug与本地name比对）
            const localVersion = this.getLocalVersion(plugin.slug);
            const hasUpdate = localVersion && this.compareVersions(plugin.version, localVersion) > 0;

            // 使用short_description，不做任何处理
            const shortDesc = plugin.short_description || '暂无描述';

            html += `
                <tr>
                    <td>
                        <div class="">
                            ${plugin.name}
                            <span onclick="viewPluginDetail('${plugin.slug}')" title="查看详情">
                                <i class="fas fa-info-circle"></i>
                            </span>
                        </div>
                        <small class="text-muted">${plugin.slug}</small>
                        ${hasUpdate ? '<div><span class="badge bg-warning text-dark"><i class="fas fa-arrow-up"></i> 有更新</span></div>' : ''}
                    </td>
                    <td>
                        ${shortDesc}
                    </td>
                    <td>
                        <span class="badge badge-success-lighten p-1">v${plugin.version}</span>
                        ${localVersion ? `<br><small class="text-success">已安装: v${localVersion}</small>` : ''}
                    </td>
                    <td>
                        <small>${plugin.author || '未知'}</small>
                    </td>
                    <td>
                        <span class="badge badge-info-lighten p-1">${categoryName}</span>
                    </td>
                    <td>
                        ${priceText}
                    </td>
                    <td>
                        ${this.renderActionButtonsWithoutDetail(plugin, hasUpdate, localVersion)}
                    </td>
                </tr>
            `;
        });

        tbody.innerHTML = html;
        this.renderPagination();
        this.hideTableLoading();
    }

    /**
     * 渲染分页组件
     */
    renderPagination() {
        const paginationContainer = document.getElementById('marketPagination');
        if (!paginationContainer || !this.pagination) return;

        const { current_page, last_page, total } = this.pagination;

        if (last_page <= 1) {
            paginationContainer.innerHTML = '';
            return;
        }

        let html = '<nav aria-label="市场分页" style="display: inline-block;"><ul class="pagination justify-content-center" style="display: inline-flex; flex-wrap: nowrap;">';

        // 上一页
        if (current_page > 1) {
            html += `<li class="page-item">
                <a class="page-link" href="#" onclick="changePage(${current_page - 1})">上一页</a>
            </li>`;
        } else {
            html += `<li class="page-item disabled">
                <span class="page-link">上一页</span>
            </li>`;
        }

        // 页码
        const startPage = Math.max(1, current_page - 2);
        const endPage = Math.min(last_page, current_page + 2);

        if (startPage > 1) {
            html += `<li class="page-item">
                <a class="page-link" href="#" onclick="changePage(1)">1</a>
            </li>`;
            if (startPage > 2) {
                html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            if (i === current_page) {
                html += `<li class="page-item active">
                    <span class="page-link">${i}</span>
                </li>`;
            } else {
                html += `<li class="page-item">
                    <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                </li>`;
            }
        }

        if (endPage < last_page) {
            if (endPage < last_page - 1) {
                html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
            }
            html += `<li class="page-item">
                <a class="page-link" href="#" onclick="changePage(${last_page})">${last_page}</a>
            </li>`;
        }

        // 下一页
        if (current_page < last_page) {
            html += `<li class="page-item">
                <a class="page-link" href="#" onclick="changePage(${current_page + 1})">下一页</a>
            </li>`;
        } else {
            html += `<li class="page-item disabled">
                <span class="page-link">下一页</span>
            </li>`;
        }

        html += '</ul></nav>';

        paginationContainer.innerHTML = html;
    }

    /**
     * 显示表格加载状态
     */
    showTableLoading() {
        const tbody = document.querySelector('#marketTable tbody');
        if (tbody) {
            tbody.innerHTML = '<tr><td colspan="7" class="text-center"><div class="loading">正在加载...</div></td></tr>';
        }
    }

    /**
     * 隐藏表格加载状态
     */
    hideTableLoading() {
        // 加载状态在renderMarketTable中处理
    }

    /**
     * 渲染状态
     */
    renderPluginStatus(plugin) {
        const isInstalled = this.checkInstalled(plugin.slug);
        const isEnabled = this.checkEnabled(plugin.slug);

        if (isInstalled && isEnabled) {
            return '<span class="status-badge enabled">已启用</span>';
        } else if (isInstalled) {
            return '<span class="status-badge disabled">已禁用</span>';
        } else {
            return '<span class="status-badge not-installed">未安装</span>';
        }
    }



    /**
     * 检查是否已购买
     */
    checkPurchased(pluginId) {
        const purchased = localStorage.getItem('purchased_plugins');
        if (purchased) {
            const list = JSON.parse(purchased);
            return list.includes(pluginId);
        }
        return false;
    }

    /**
     * 检查是否已安装（通过slug与本地name比对）
     */
    checkInstalled(pluginSlug) {
        // 从本地列表中查找对应的插件
        if (this.localPlugins && this.localPlugins.length > 0) {
            return this.localPlugins.some(plugin => plugin.name === pluginSlug);
        }
        return false;
    }

    /**
     * 检查是否已启用（通过slug与本地插件name比对）
     */
    checkEnabled(pluginSlug) {
        // 从本地列表中查找对应的应用
        if (this.localPlugins && this.localPlugins.length > 0) {
            const localPlugin = this.localPlugins.find(plugin => plugin.name === pluginSlug);
            return localPlugin ? localPlugin.status === 'enabled' : false;
        }
        return false;
    }

    /**
     * 获取本地插件版本（通过slug查找本地插件name）
     */
    getLocalVersion(pluginSlug) {
        // 从本地列表中查找对应的插件
        if (this.localPlugins && this.localPlugins.length > 0) {
            const localPlugin = this.localPlugins.find(plugin => plugin.name === pluginSlug);
            // console.log(`查找插件 ${pluginSlug}:`, localPlugin ? `找到版本 ${localPlugin.version}` : '未找到');
            return localPlugin ? localPlugin.version : null;
        }
        // console.log(`本地列表为空，无法查找 ${pluginSlug}`);
        return null;
    }

    /**
     * 比较版本号
     */
    compareVersions(version1, version2) {
        const v1parts = version1.split('.').map(Number);
        const v2parts = version2.split('.').map(Number);

        for (let i = 0; i < Math.max(v1parts.length, v2parts.length); i++) {
            const v1part = v1parts[i] || 0;
            const v2part = v2parts[i] || 0;

            if (v1part > v2part) return 1;
            if (v1part < v2part) return -1;
        }
        return 0;
    }

    /**
     * 过滤插件 - 重新从API获取数据
     */
    async filterPlugins() {
        // 重新从API获取数据，而不是本地过滤
        await this.loadMarketPlugins(1); // 重置到第一页
    }

    /**
     * 加载市场插件 - 支持筛选参数
     */
    async loadMarketPlugins(page = 1) {
        try {
            this.showTableLoading();

            // 构建请求参数
            const params = new URLSearchParams({
                page: page,
                limit: 10
            });

            // 添加筛选参数
            const search = document.getElementById('marketSearch')?.value.trim();
            if (search) {
                params.append('search', search);
            }

            if (this.currentType) {
                params.append('type', this.currentType);
            }

            if (this.currentCategory) {
                params.append('category_id', this.currentCategory);
            }

            if (this.currentPrice) {
                params.append('price_type', this.currentPrice);
            }

            // token由后端统一处理，前端不需要传递

            // 调用插件市场控制器
            const response = await fetch('/adminapi/plugin/market/getPlugins?' + params);
            const data = await response.json();

            if (data.code === 1) {
                // 根据API文档，数据结构应该是 data.plugins
                this.allPlugins = data.data.plugins || data.data.list || [];
                this.filteredPlugins = [...this.allPlugins];
                this.pagination = data.data.pagination || null;
                this.renderMarketTable();
            } else {
                this.showError('加载市场失败: ' + (data.msg || '未知错误'));
                this.allPlugins = [];
                this.filteredPlugins = [];
                this.pagination = null;
                this.renderMarketTable();
            }
        } catch (error) {
            this.showError('连接市场失败，请检查网络连接或稍后重试');
            this.allPlugins = [];
            this.filteredPlugins = [];
            this.pagination = null;
            this.renderMarketTable();
        }
    }

    /**
     * 搜索插件
     */
    async searchPlugins(keyword, category = '', priceType = '', type = '') {
        try {
            this.showTableLoading();

            const params = new URLSearchParams({
                page: 1,
                limit: 10,
                keyword: keyword
            });

            if (category) params.append('category', category);
            if (priceType) params.append('price_type', priceType);
            if (type) params.append('type', type);

            // token由后端统一处理，前端不需要传递

            const response = await fetch('/adminapi/plugin/market/getPlugins?' + params);
            const data = await response.json();

            if (data.code === 1) {
                this.filteredPlugins = data.data.plugins || data.data.list || [];
                this.renderMarketTable();
            } else {
                this.showError('搜索失败: ' + (data.msg || '未知错误'));
            }
        } catch (error) {
            this.showError('搜索失败，请稍后重试');
        }
    }
    /**
     * 启用插件
     */
    async enablePlugin(pluginId) {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 500));

            // 更新本地状态
            let enabled = localStorage.getItem('enabled_plugins');
            enabled = enabled ? JSON.parse(enabled) : [];
            if (!enabled.includes(pluginId)) {
                enabled.push(pluginId);
                localStorage.setItem('enabled_plugins', JSON.stringify(enabled));
            }

            this.updateMarketPluginStatus(pluginId, 'enabled');
            layer.msg('启用成功', { icon: 1, time: 1500 });
        } catch (error) {
            layer.msg('启用失败: ' + error.message, { icon: 2, time: 3000 });
        }
    }

    /**
     * 禁用插件
     */
    async disablePlugin(pluginId) {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 300));

            // 更新本地状态
            let enabled = localStorage.getItem('enabled_plugins');
            enabled = enabled ? JSON.parse(enabled) : [];
            const index = enabled.indexOf(pluginId);
            if (index > -1) {
                enabled.splice(index, 1);
                localStorage.setItem('enabled_plugins', JSON.stringify(enabled));
            }

            this.updateMarketPluginStatus(pluginId, 'disabled');
            layer.msg('禁用成功', { icon: 1, time: 1500 });
        } catch (error) {
            layer.msg('禁用失败: ' + error.message, { icon: 2, time: 3000 });
        }
    }

    /**
     * 卸载插件
     */
    async uninstallPlugin(pluginId) {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 300));

            // 更新本地状态
            let installed = localStorage.getItem('installed_plugins');
            installed = installed ? JSON.parse(installed) : [];
            const installedIndex = installed.indexOf(pluginId);
            if (installedIndex > -1) {
                installed.splice(installedIndex, 1);
                localStorage.setItem('installed_plugins', JSON.stringify(installed));
            }

            let enabled = localStorage.getItem('enabled_plugins');
            enabled = enabled ? JSON.parse(enabled) : [];
            const enabledIndex = enabled.indexOf(pluginId);
            if (enabledIndex > -1) {
                enabled.splice(enabledIndex, 1);
                localStorage.setItem('enabled_plugins', JSON.stringify(enabled));
            }

            this.updateMarketPluginStatus(pluginId, 'not-installed');
            layer.msg('卸载成功', { icon: 1, time: 1500 });
        } catch (error) {
            layer.msg('卸载失败: ' + error.message, { icon: 2, time: 3000 });
        }
    }

    /**
     * 安装插件
     */
    async installPlugin(pluginId) {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 500));

            // 更新本地状态
            let installed = localStorage.getItem('installed_plugins');
            installed = installed ? JSON.parse(installed) : [];
            if (!installed.includes(pluginId)) {
                installed.push(pluginId);
                localStorage.setItem('installed_plugins', JSON.stringify(installed));
            }

            this.updateMarketPluginStatus(pluginId, 'disabled');
            layer.msg('安装成功', { icon: 1, time: 1500 });
        } catch (error) {
            layer.msg(error.message, { icon: 2, time: 3000 });
        }
    }

    /**
     * 显示支付弹出层
     */
    async showPaymentModal(pluginId, pluginName, price) {
        // 检查是否已登录
        if (!this.marketUser || !this.marketUser.token) {
            layer.msg('请先登录', { icon: 2 });
            return;
        }

        const modal = document.getElementById('paymentModal');
        const orderTitle = document.getElementById('payOrderTitle');
        const orderPrice = document.getElementById('payOrderPrice');
        const payMethod = document.getElementById('payMethod');
        const orderStatus = document.getElementById('payOrderStatus');

        // 初始化订单信息
        orderTitle.textContent = `购买（${pluginName}）`;
        orderPrice.textContent = `¥ ${price}`;
        payMethod.textContent = '支付宝';
        orderStatus.textContent = '待支付';

        // 存储当前订单信息，用于支付方式切换
        this.currentOrder = {
            pluginId: pluginId,
            pluginName: pluginName,
            price: price,
            itemType: 'plugin'
        };

        modal.style.display = 'flex';

        // 默认使用支付宝创建订单
        await this.createPaymentOrder(pluginId, 'plugin', 'alipay', price);
    }

    /**
     * 创建支付订单
     */
    async createPaymentOrder(itemId, itemType, paymentMethod, price) {
        try {
            const loadingIndex = layer.load(1, {
                shade: [0.3, '#000']
            });

            // 调用本地API代理到市场的创建订单接口
            const response = await fetch('/adminapi/plugin/market/createPaymentOrder', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    item_type: itemType,        // plugin 或 template
                    item_id: parseInt(itemId),  // 商品ID
                    payment_method: paymentMethod // alipay 或 wechat
                })
            });

            layer.close(loadingIndex);

            const data = await response.json();

            if (data.code === 1 || data.success === true) {
                // 订单创建成功，显示支付信息
                const orderData = data.data || data;
                this.displayPaymentInfo(orderData);
            } else {
                layer.msg('创建订单失败: ' + (data.message || data.msg || '未知错误'), { icon: 2 });
                this.closePaymentModal();
            }
        } catch (error) {
            layer.close(loadingIndex);
            layer.msg('创建订单失败: ' + error.message, { icon: 2 });
            this.closePaymentModal();
        }
    }

    /**
     * 显示支付信息
     */
    displayPaymentInfo(orderData) {
        console.log(orderData);

        // 更新订单信息
        const orderNo = document.getElementById('payOrderNo');
        const orderTitle = document.getElementById('payOrderTitle');
        const orderPrice = document.getElementById('payOrderPrice');
        const itemType = document.getElementById('payItemType');
        const orderStatus = document.getElementById('payOrderStatus');
        const qrContainer = document.getElementById('paymentQR');

        // 显示订单信息
        orderNo.textContent = orderData.order_no || orderData.trade_no || 'N/A';

        if (orderData.item_name) {
            orderTitle.textContent = `购买（${orderData.item_name}）`;
        }

        if (orderData.amount) {
            orderPrice.textContent = `¥ ${orderData.amount}`;
        }

        if (orderData.item_type) {
            itemType.textContent = orderData.item_type === 'plugin' ? '插件' : '模板';
        }

        // 更新订单状态
        const statusMap = {
            'pending': '待支付',
            'paid': '已支付',
            'cancelled': '已取消',
            'failed': '支付失败'
        };
        orderStatus.textContent = statusMap[orderData.status] || '待支付';

        // 根据状态更新样式
        orderStatus.className = 'status';
        if (orderData.status === 'paid') {
            orderStatus.style.background = '#dcfce7';
            orderStatus.style.color = '#166534';
        } else if (orderData.status === 'failed' || orderData.status === 'cancelled') {
            orderStatus.style.background = '#fee2e2';
            orderStatus.style.color = '#dc2626';
        }

        // 显示支付二维码
        if (orderData.qr_code) {
            qrContainer.innerHTML = `
                <img src="${orderData.qr_code}" alt="支付二维码" style="width: 200px; height: 200px; border: 1px solid #ddd; border-radius: 8px;">
            `;
        } else if (orderData.payment_data && orderData.payment_data.url) {
            // 使用返回的支付URL生成二维码
            this.generateQRCode(orderData.payment_data.url);
        } else if (orderData.payment_url) {
            // 兼容其他格式
            this.generateQRCode(orderData.payment_url);
        } else {
            qrContainer.innerHTML = `
                <div style="width: 200px; height: 200px; background: #f0f0f0; display: flex; align-items: center; justify-content: center; border: 1px solid #ddd; border-radius: 8px;">
                    支付信息加载中...
                </div>
            `;
        }

        // 延迟15秒后开始轮询订单状态
        setTimeout(() => {
            this.startPaymentPolling(orderData.order_no || orderData.trade_no);
        }, 15000);
    }

    /**
     * 生成二维码
     */
    generateQRCode(url) {
        const qrContainer = document.getElementById('paymentQR');

        if (!url) {
            qrContainer.innerHTML = `
                <div style="width: 200px; height: 200px; background: #f0f0f0; display: flex; align-items: center; justify-content: center; border: 1px solid #ddd; border-radius: 8px;">
                    支付链接无效
                </div>
            `;
            return;
        }

        // 使用jQuery QRCode库生成二维码
        try {
            // 创建一个唯一的ID，避免冲突
            const qrId = 'qrcode_' + Date.now();

            qrContainer.innerHTML = `
                <div style="text-align: center;">
                    <div id="${qrId}" style="display: inline-block; padding: 10px; background: #fff; border: 1px solid #ddd; border-radius: 8px;"></div>
                    <div style="margin-top: 8px; font-size: 12px; color: #666;">
                       <a href="${url}" target="_blank" style="color: #007bff; text-decoration: underline;display:none">点击直接支付</a>
                    </div>
                </div>
            `;

            // 等待DOM更新后生成二维码
            setTimeout(() => {
                try {
                    $(`#${qrId}`).qrcode({
                        text: url,
                        width: 180,
                        height: 180
                    });
                } catch (qrError) {
                    console.error('二维码生成失败:', qrError);
                    // 降级方案：显示链接
                    qrContainer.innerHTML = `
                        <div style="width: 200px; height: 200px; background: #f0f0f0; display: flex; align-items: center; justify-content: center; border: 1px solid #ddd; border-radius: 8px; flex-direction: column;">
                            <div style="margin-bottom: 10px;">二维码生成失败</div>
                            <a href="${url}" target="_blank" style="color: #007bff; text-decoration: underline;">点击直接支付</a>
                        </div>
                    `;
                }
            }, 100);

        } catch (error) {
            console.error('二维码生成失败:', error);
            // 降级方案：显示链接
            qrContainer.innerHTML = `
                <div style="width: 200px; height: 200px; background: #f0f0f0; display: flex; align-items: center; justify-content: center; border: 1px solid #ddd; border-radius: 8px; flex-direction: column;">
                    <div style="margin-bottom: 10px;">二维码生成失败</div>
                    <a href="${url}" target="_blank" style="color: #007bff; text-decoration: underline;">点击直接支付</a>
                </div>
            `;
        }
    }

    /**
     * 开始轮询支付状态
     */
    startPaymentPolling(orderNo) {
        if (!orderNo) return;

        // 清理之前的轮询
        if (this.paymentPollingInterval) {
            clearInterval(this.paymentPollingInterval);
        }

        this.paymentPollingInterval = setInterval(async () => {
            try {
                const response = await fetch('/adminapi/plugin/market/checkPaymentStatus', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        order_no: orderNo
                    })
                });

                const data = await response.json();

                if (data.code === 1 && data.data) {
                    // 更新订单状态显示
                    this.updateOrderStatus(data.data);

                    if (data.data.status === 'paid') {
                        // 支付成功
                        clearInterval(this.paymentPollingInterval);
                        this.paymentPollingInterval = null;
                        layer.msg('支付成功！', { icon: 1 });
                        this.closePaymentModal();

                        // 刷新本地列表和市场列表（会自动获取最新的购买状态）
                        await this.loadLocalPlugins();
                        this.loadMarketPlugins(1);
                    } else if (data.data.status === 'cancelled' || data.data.status === 'failed') {
                        // 支付失败或取消
                        clearInterval(this.paymentPollingInterval);
                        this.paymentPollingInterval = null;
                        layer.msg('支付失败或已取消', { icon: 2 });
                        this.closePaymentModal();
                    }
                }
            } catch (error) {
                console.error('检查支付状态失败:', error);
            }
        }, 5000); // 每5秒检查一次

        // 5分钟后停止轮询
        setTimeout(() => {
            if (this.paymentPollingInterval) {
                clearInterval(this.paymentPollingInterval);
                this.paymentPollingInterval = null;
            }
        }, 300000);
    }

    /**
     * 更新订单状态显示
     */
    updateOrderStatus(orderData) {
        const orderStatus = document.getElementById('payOrderStatus');
        if (!orderStatus) return;

        // 更新订单状态
        const statusMap = {
            'pending': '待支付',
            'paid': '已支付',
            'cancelled': '已取消',
            'failed': '支付失败'
        };
        orderStatus.textContent = statusMap[orderData.status] || '未知状态';

        // 根据状态更新样式
        orderStatus.className = 'status';
        if (orderData.status === 'paid') {
            orderStatus.style.background = '#dcfce7';
            orderStatus.style.color = '#166534';
        } else if (orderData.status === 'failed' || orderData.status === 'cancelled') {
            orderStatus.style.background = '#fee2e2';
            orderStatus.style.color = '#dc2626';
        } else {
            orderStatus.style.background = '#fef3c7';
            orderStatus.style.color = '#92400e';
        }
    }



    /**
     * 切换支付方式
     */
    async switchPaymentMethod(method) {
        if (!this.currentOrder) {
            layer.msg('订单信息丢失，请重新购买', { icon: 2 });
            return;
        }

        // 更新支付方式选择状态
        document.querySelectorAll('.payment-method').forEach(el => {
            el.classList.remove('active');
        });
        document.querySelector(`[data-method="${method}"]`).classList.add('active');

        // 更新支付按钮文字
        const scanBtn = document.querySelector('.payment-scan-btn');
        if (method === 'alipay') {
            scanBtn.innerHTML = '<i class="icon-scan"></i> 请使用支付宝扫一扫<br>扫描二维码支付';
        } else if (method === 'wechat') {
            scanBtn.innerHTML = '<i class="icon-scan"></i> 请使用微信扫一扫<br>扫描二维码支付';
        }

        // 重新创建订单
        await this.createPaymentOrder(
            this.currentOrder.pluginId,
            this.currentOrder.itemType,
            method,
            this.currentOrder.price
        );
    }

    /**
     * 更新市场插件状态（不重新渲染表格）
     */
    updateMarketPluginStatus(pluginId, status) {
        const row = document.querySelector(`tr[data-plugin-id="${pluginId}"]`);
        if (!row) return;

        // 更新状态列
        const statusCell = row.querySelector('.plugin-status');
        if (statusCell) {
            const statusBadge = statusCell.querySelector('.status-badge');
            if (statusBadge) {
                statusBadge.className = `status-badge ${status}`;
                switch (status) {
                    case 'enabled':
                        statusBadge.textContent = '已启用';
                        break;
                    case 'disabled':
                        statusBadge.textContent = '已禁用';
                        break;
                    case 'not-installed':
                        statusBadge.textContent = '未安装';
                        break;
                }
            }
        }

        // 更新操作按钮
        const actionsCell = row.querySelector('.plugin-actions');
        if (actionsCell) {
            const plugin = this.filteredPlugins.find(p => p.id === pluginId);
            if (plugin) {
                actionsCell.innerHTML = this.renderActionButtons({
                    ...plugin,
                    // 临时更新状态用于按钮渲染
                    _tempStatus: status
                });
            }
        }
    }

    /**
     * 渲染操作按钮（支持临时状态和升级）
     */
    renderActionButtons(plugin, hasUpdate = false, localVersion = null) {
        const status = plugin._tempStatus || null;
        const isInstalled = status ? (status !== 'not-installed') : (localVersion !== null);
        const isEnabled = status ? (status === 'enabled') : this.checkEnabled(plugin.slug);
        const price = parseFloat(plugin.price) || 0;

        // 使用API返回的购买状态字段
        const isPurchased = plugin.is_purchased || false;
        const isOwn = plugin.is_own || false;
        const canDownload = plugin.can_download || false;

        let buttons = [];

        // 优先检查是否有更新
        if (hasUpdate && isInstalled) {
            // 有更新的已安装插件显示"升级"按钮
            buttons.push(`<button class="btn btn-sm btn-warning" onclick="upgradePlugin('${plugin.id}', '${plugin.name}', '${plugin.slug}')" title="升级插件">
                <i class="fas fa-arrow-up"></i> 升级
            </button>`);
        } else if (isInstalled) {
            // 已安装且无更新的插件显示"已安装"状态
            buttons.push(`<span>
                <i class="fas fa-check"></i> 已安装
            </span>`);
        } else {
            // 未安装的插件
            if (!this.marketUser) {
                // 未登录 - 显示登录按钮
                buttons.push(`<button class="btn btn-sm btn-outline-primary" onclick="showLoginModal()" title="登录后安装">
                    <i class="fas fa-sign-in-alt"></i> 登录安装
                </button>`);
            } else if (price === 0 || isOwn) {
                // 免费插件或自己的插件 - 直接显示安装按钮
                if (canDownload) {
                    buttons.push(`<button class="btn btn-sm btn-success" onclick="downloadAndInstall('${plugin.id}', '${plugin.slug}')" title="安装插件">
                        <i class="fas fa-download"></i> 安装
                    </button>`);
                } else {
                    buttons.push(`<button class="btn btn-sm btn-secondary" disabled title="无法下载">
                        <i class="fas fa-ban"></i> 无法下载
                    </button>`);
                }
            } else {
                // 付费插件
                if (isPurchased || isOwn) {
                    // 已购买或自己的插件
                    if (canDownload) {
                        buttons.push(`<button class="btn btn-sm btn-success" onclick="downloadAndInstall('${plugin.id}', '${plugin.slug}')" title="安装已购买的插件">
                            <i class="fas fa-download"></i> 安装
                        </button>`);
                    } else {
                        buttons.push(`<span class="badge bg-info">
                            <i class="fas fa-check-circle"></i> 已购买
                        </span>`);
                    }
                } else {
                    // 未购买的付费插件
                    buttons.push(`<button class="btn btn-sm btn-warning" onclick="purchasePlugin('${plugin.id}', '${plugin.name}', ${price})" title="购买插件">
                        <i class="fas fa-shopping-cart"></i> 购买
                    </button>`);
                }
            }
        }

        // 添加详情按钮
        buttons.push(`<button class="btn btn-sm btn-outline-info" onclick="viewPluginDetail('${plugin.slug}')" title="查看详情">
            <i class="fas fa-info-circle"></i>
        </button>`);

        return `<div class="btn-group btn-group-sm" role="group">${buttons.join('')}</div>`;
    }

    /**
     * 渲染操作按钮（不包含详情按钮）
     */
    renderActionButtonsWithoutDetail(plugin, hasUpdate = false, localVersion = null) {
        const status = plugin._tempStatus || null;
        const isInstalled = status ? (status !== 'not-installed') : (localVersion !== null);
        const isEnabled = status ? (status === 'enabled') : this.checkEnabled(plugin.slug);
        const price = parseFloat(plugin.price) || 0;

        // 使用API返回的购买状态字段
        const isPurchased = plugin.is_purchased || false;
        const isOwn = plugin.is_own || false;
        const canDownload = plugin.can_download || false;

        let buttons = [];

        // 优先检查是否有更新
        if (hasUpdate && isInstalled) {
            // 有更新的已安装插件显示"升级"按钮
            buttons.push(`<button class="btn btn-sm btn-warning" onclick="upgradePlugin('${plugin.id}', '${plugin.name}', '${plugin.slug}')" title="升级插件">
                <i class="fas fa-arrow-up"></i> 升级
            </button>`);
        } else if (isInstalled) {
            // 已安装且无更新的插件显示"已安装"状态
            buttons.push(`<span class=">
                <i class="fas fa-check"></i> 已安装
            </span>`);
        } else {
            // 未安装的插件
            if (!this.marketUser) {
                // 未登录 - 显示登录按钮
                buttons.push(`<button class="btn btn-sm btn-outline-primary" onclick="showLoginModal()" title="登录后安装">
                    <i class="fas fa-sign-in-alt"></i> 登录安装
                </button>`);
            } else if (price === 0 || isOwn) {
                // 免费插件或自己的插件 - 直接显示安装按钮
                if (canDownload) {
                    buttons.push(`<button class="btn btn-sm btn-success" onclick="downloadAndInstall('${plugin.id}', '${plugin.slug}')" title="安装插件">
                        <i class="fas fa-download"></i> 安装
                    </button>`);
                } else {
                    buttons.push(`<button class="btn btn-sm btn-secondary" disabled title="无法下载">
                        <i class="fas fa-ban"></i> 无法下载
                    </button>`);
                }
            } else {
                // 付费插件
                if (isPurchased || isOwn) {
                    // 已购买或自己的插件
                    if (canDownload) {
                        buttons.push(`<button class="btn btn-sm btn-success" onclick="downloadAndInstall('${plugin.id}', '${plugin.slug}')" title="安装已购买的插件">
                            <i class="fas fa-download"></i> 安装
                        </button>`);
                    } else {
                        buttons.push(`<span class="badge bg-info">
                            <i class="fas fa-check-circle"></i> 已购买
                        </span>`);
                    }
                } else {
                    // 未购买的付费插件
                    buttons.push(`<button class="btn btn-sm btn-warning" onclick="purchasePlugin('${plugin.id}', '${plugin.name}', ${price})" title="购买插件">
                        <i class="fas fa-shopping-cart"></i> 购买
                    </button>`);
                }
            }
        }

        // 不添加详情按钮，因为已经在名称列中了
        return `<div class="btn-group btn-group-sm" role="group">${buttons.join('')}</div>`;
    }

    /**
     * 关闭支付弹窗
     */
    closePaymentModal() {
        const modal = document.getElementById('paymentModal');
        if (modal) {
            modal.style.display = 'none';
        }

        // 清理当前订单信息
        this.currentOrder = null;

        // 停止所有轮询
        if (this.paymentPollingInterval) {
            clearInterval(this.paymentPollingInterval);
            this.paymentPollingInterval = null;
        }

        // 重置支付弹窗内容
        this.resetPaymentModal();
    }

    /**
     * 重置支付弹窗内容
     */
    resetPaymentModal() {
        const orderTitle = document.getElementById('payOrderTitle');
        const orderNo = document.getElementById('payOrderNo');
        const orderPrice = document.getElementById('payOrderPrice');
        const itemType = document.getElementById('payItemType');
        const orderStatus = document.getElementById('payOrderStatus');
        const qrContainer = document.getElementById('paymentQR');

        if (orderTitle) orderTitle.textContent = '-';
        if (orderNo) orderNo.textContent = '-';
        if (orderPrice) orderPrice.textContent = '¥ 0.00';
        if (itemType) itemType.textContent = '-';
        if (orderStatus) {
            orderStatus.textContent = '待支付';
            orderStatus.className = 'status';
            orderStatus.style.background = '#fef3c7';
            orderStatus.style.color = '#92400e';
        }
        if (qrContainer) {
            qrContainer.innerHTML = `
                <div style="width: 200px; height: 200px; background: #f0f0f0; display: flex; align-items: center; justify-content: center; border: 1px solid #ddd; border-radius: 8px;">
                    二维码加载中...
                </div>
            `;
        }
    }


}

// 选择类型
function selectType(element, type) {
    // 更新UI
    document.querySelectorAll('[data-type]').forEach(el => el.classList.remove('active'));
    element.classList.add('active');

    // 更新状态
    window.marketManager.currentType = type;

    // 显示或隐藏分类区域
    const categorySection = document.getElementById('categorySection');
    if (type === '' || type === 'all') {
        // 选择"全部"时隐藏分类
        categorySection.style.display = 'none';
    } else {
        // 选择"插件"或"模板"时显示分类并加载
        categorySection.style.display = 'block';
        window.marketManager.loadCategories();
    }

    // 重置分类选择
    window.marketManager.currentCategory = '';

    // 执行筛选
    filterMarketPlugins();
}

// 选择分类
function selectCategory(element, category) {
    // 更新UI - 移除所有分类按钮的active状态
    document.querySelectorAll('[data-category]').forEach(el => el.classList.remove('active'));
    // 添加当前按钮的active状态
    element.classList.add('active');

    // 更新状态
    if (window.marketManager) {
        window.marketManager.currentCategory = category;
    }

    // 执行筛选
    filterMarketPlugins();
}

// 选择价格
function selectPrice(element, price) {
    // 更新UI
    document.querySelectorAll('[data-price]').forEach(el => el.classList.remove('active'));
    element.classList.add('active');

    // 更新状态
    window.marketManager.currentPrice = price;

    // 执行筛选
    filterMarketPlugins();
}

// 过滤市场插件
async function filterMarketPlugins() {
    if (window.marketManager) {
        await window.marketManager.filterPlugins();
    }
}

// 切换页面
async function changePage(page) {
    if (window.marketManager) {
        await window.marketManager.loadMarketPlugins(page);
    }
}

// 下载并安装插件
async function downloadAndInstall(pluginId, pluginSlug) {
    // 检查是否登录
    if (!window.marketManager?.marketUser) {
        layer.msg('请先登录市场账户', { icon: 2 });
        showLoginModal();
        return;
    }

    // 获取插件信息
    const plugin = window.marketManager?.filteredPlugins?.find(p => p.id == pluginId);
    if (!plugin) {
        layer.msg('信息不存在', { icon: 2 });
        return;
    }

    const loadingIndex = layer.load(0);

    try {
        // 调用下载安装API，携带token和type
        const response = await fetch('/adminapi/plugin/download/downloadAndInstall', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                plugin_slug: pluginSlug,
                plugin_id: pluginId,
                type: plugin.type || 'plugin'  // 插件类型：plugin 或 template
            })
        });

        const data = await response.json();
        layer.close(loadingIndex);

        if (data.code === 1) {
            layer.msg('安装成功！', { icon: 1 });
            // 重新加载本地列表和市场列表
            if (window.marketManager) {
                await window.marketManager.loadLocalPlugins();
                await window.marketManager.loadMarketPlugins(window.marketManager.pagination?.current_page || 1);
            }
        } else {
            layer.msg( (data.msg || '未知错误'), { icon: 2 });
        }

    } catch (error) {
        layer.close(loadingIndex);
        layer.msg( error.message, { icon: 2 });
    }
}

// 查看插件详情
function viewPluginDetail(pluginId) {
    // 这里可以打开插件详情模态框或跳转到详情页
    layer.open({
        type: 2,
        title: '详情',
        shadeClose: true,
        shade: 0.3,
        area: ['80%', '80%'],
        content: `/adminapi/plugin/market/detail?id=${pluginId}`
    });
}

// 刷新市场
function refreshMarket() {
    if (window.marketManager) {
        window.marketManager.loadMarketPlugins();
    }
}

// 从市场安装插件
async function installFromMarket(pluginId) {
    if (window.marketManager) {
        await window.marketManager.installPlugin(pluginId);
    }
}

// 启用市场插件
async function enableMarketPlugin(pluginId) {
    if (window.marketManager) {
        await window.marketManager.enablePlugin(pluginId);
    }
}

// 禁用市场插件
async function disableMarketPlugin(pluginId) {
    if (window.marketManager) {
        await window.marketManager.disablePlugin(pluginId);
    }
}

// 卸载市场插件
async function uninstallMarketPlugin(pluginId) {
    layer.confirm('确定要卸载吗？', {
        icon: 3,
        title: '确认卸载',
        btn: ['确定', '取消']
    }, async function (index) {
        layer.close(index);
        if (window.marketManager) {
            await window.marketManager.uninstallPlugin(pluginId);
        }
    });
}

// 购买插件
function purchasePlugin(pluginId, pluginName, price) {
    if (window.marketManager) {
        window.marketManager.showPaymentModal(pluginId, pluginName, price);
    }
}

// 升级插件
function upgradePlugin(pluginId, pluginName, pluginSlug) {
    // 检查是否登录
    if (!window.marketManager?.marketUser) {
        layer.msg('请先登录市场账户', { icon: 2 });
        showLoginModal();
        return;
    }

    // 获取插件信息
    const plugin = window.marketManager?.filteredPlugins?.find(p => p.id == pluginId);
    if (!plugin) {
        layer.msg('应用不存在', { icon: 2 });
        return;
    }

    layer.confirm(`确定要升级"${pluginName}"吗？`, {
        icon: 1,
        title: '确认升级',
        btn: ['确定', '取消']
    }, async function (index) {
        layer.close(index);

        const loadingIndex = layer.load(0);

        try {
            // 调用下载安装API，传递升级标识和token
            const response = await fetch('/adminapi/plugin/download/downloadAndInstall', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    plugin_slug: pluginSlug,
                    plugin_id: pluginId,
                    type: plugin.type || 'plugin',  // 插件类型：plugin 或 template
                    is_upgrade: true
                })
            });

            const data = await response.json();
            layer.close(loadingIndex);

            if (data.code === 1) {
                layer.msg('升级成功！', { icon: 1 });
                // 重新加载本地列表和市场列表
                if (window.marketManager) {
                    await window.marketManager.loadLocalPlugins();
                    await window.marketManager.loadMarketPlugins(window.marketManager.pagination?.current_page || 1);
                }
            } else {
                layer.msg('升级失败: ' + (data.msg || '未知错误'), { icon: 2 });
            }
        } catch (error) {
            layer.close(loadingIndex);
            layer.msg('升级失败: ' + error.message, { icon: 2 });
        }
    });
}

// 关闭支付弹出层
function closePaymentModal() {
    if (window.marketManager) {
        window.marketManager.closePaymentModal();
    } else {
        const modal = document.getElementById('paymentModal');
        modal.style.display = 'none';
    }
}

// 选择支付方式
function selectPaymentMethod(method) {
    if (window.marketManager) {
        window.marketManager.switchPaymentMethod(method);
    }
}



// 显示登录弹出层
function showLoginModal() {
    layer.open({
        type: 1,
        title: '登录应用市场',
        area: ['400px', '400px'],
        content: `
            <div style="padding: 20px;">
                <form id="marketLoginForm">
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500;">邮箱:</label>
                        <input type="email" name="username" required
                               style="width: 100%; padding: 8px 0; border: 1px solid #ddd; border-radius: 4px;">
                    </div>
                    <div style="margin-bottom: 20px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500;">密码:</label>
                        <input type="password" name="password" required
                               style="width: 100%; padding: 8px 0; border: 1px solid #ddd; border-radius: 4px;">
                    </div>
                    <div style="text-align: center;">
                        <button type="submit" class="btn btn-primary" style="margin-right: 10px;">登录</button>
                        <button type="button" class="btn btn-secondary" onclick="layer.closeAll()">取消</button>
                    </div>
                </form>
                <div style="margin-top: 15px; text-align: center; font-size: 12px; color: #6c757d;">
                    还没有账号？<a href="/api/index/goMarketLoginPage" target="_blank" style="color: #007bff;">立即注册</a>
                </div>
            </div>
        `,
        success: function () {
            document.getElementById('marketLoginForm').addEventListener('submit', handleLogin);
        }
    });
}

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    const formData = new FormData(e.target);
    const username = formData.get('username');
    const password = formData.get('password');

    const loadingIndex = layer.load(1);

    try {
        // 调用真实的登录API
        const response = await fetch('/adminapi/plugin/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                email: username, // 支持邮箱登录
                password: password
            })
        });

        const data = await response.json();

        if (data.code === 1) {
            // 登录成功
            const userData = data.data.user_info;
            userData.token = data.data.token;
            userData.email = data.data.email;

            window.marketManager.marketUser = userData;
            window.marketManager.saveLoginData(userData);

            layer.close(loadingIndex);
            layer.closeAll();
            layer.msg('登录成功！', { icon: 1 });

            // 登录成功后刷新列表
            window.marketManager.loadMarketPlugins(1);
        } else {
            layer.close(loadingIndex);
            layer.msg('登录失败: ' + (data.msg || '未知错误'), { icon: 2 });
        }

    } catch (error) {
        layer.close(loadingIndex);
        layer.msg('登录失败: ' + error.message, { icon: 2 });
    }
}

// 快速筛选函数
function quickFilter(element, filterType) {
    // 移除所有按钮的active状态
    document.querySelectorAll('[data-filter]').forEach(el => el.classList.remove('active'));
    // 添加当前按钮的active状态
    element.classList.add('active');

    // 更新筛选状态
    if (window.marketManager) {
        // 重置筛选条件
        window.marketManager.currentType = '';
        window.marketManager.currentCategory = '';
        window.marketManager.currentPrice = '';

        // 根据筛选类型设置条件
        switch(filterType) {
            case 'all':
                // 全部应用，不设置任何筛选条件
                hideCategorySection();
                break;
            case 'plugin':
                window.marketManager.currentType = 'plugin';
                showCategorySection();
                loadCategoriesForType('plugin');
                break;
            case 'template':
                window.marketManager.currentType = 'template';
                showCategorySection();
                loadCategoriesForType('template');
                break;
            case 'free':
                window.marketManager.currentPrice = 'free';
                hideCategorySection();
                break;
            case 'paid':
                window.marketManager.currentPrice = 'paid';
                hideCategorySection();
                break;
        }
    }

    // 执行筛选
    filterMarketPlugins();
}

// 显示分类区域
function showCategorySection() {
    const categorySection = document.getElementById('categorySection');
    if (categorySection) {
        categorySection.style.display = 'block';
    }
}

// 隐藏分类区域
function hideCategorySection() {
    const categorySection = document.getElementById('categorySection');
    if (categorySection) {
        categorySection.style.display = 'none';
    }
    // 重置分类选择
    if (window.marketManager) {
        window.marketManager.currentCategory = '';
    }
}

// 为指定类型加载分类
function loadCategoriesForType(type) {
    if (window.marketManager) {
        window.marketManager.loadCategories(type);
    }
}

// 搜索市场应用
function searchMarket() {
    const searchInput = document.getElementById('marketSearch');
    if (searchInput && window.marketManager) {
        window.marketManager.currentSearch = searchInput.value.trim();
        filterMarketPlugins();
    }
}

// 清空搜索
function clearMarketSearch() {
    const searchInput = document.getElementById('marketSearch');
    if (searchInput) {
        searchInput.value = '';
        if (window.marketManager) {
            window.marketManager.currentSearch = '';
            filterMarketPlugins();
        }
    }
}

// 搜索框回车事件
function handleMarketSearchKeypress(event) {
    if (event.key === 'Enter') {
        searchMarket();
    }
}

// 初始化市场管理器
document.addEventListener('DOMContentLoaded', () => {
    // 确保PluginManager已加载
    if (typeof PluginManager !== 'undefined') {
        window.marketManager = new MarketManager();
    } else {
        console.error('PluginManager未定义，无法初始化MarketManager');
    }
});